package com.ddsso.auth.web.filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.filter.authc.AuthenticationFilter;

import com.ddsso.auth.web.vo.AuthResponseCode;
/**
 * @author zdd
 * @package com.ddsso.auth.web.filter
 * @Time Created by zdd on 2016/11/2.
 * @description 认证过滤
 */
public class PassThruAuthenticationFilter extends AuthenticationFilter  {

    // json content type
    private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8";
    // 未登录的响应内容
    private static final String NOT_LOGINED_RESPONSE = String.format("{\"success\": false, \"code\":%s,\"message\":\"%s\"}",
            AuthResponseCode.NOT_LOGIN.getCode(), AuthResponseCode.NOT_LOGIN.getMessage());

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            return true;
        }

        // page
        if (!isAjaxRequest((HttpServletRequest) request)) {
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }

        // ajax
        response.setContentType(JSON_CONTENT_TYPE);
        response.getWriter().append(NOT_LOGINED_RESPONSE).flush();
        return false;
    }

    /**
     * 是否 ajax 请求
     */
    public boolean isAjaxRequest(HttpServletRequest request) {
        if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
            return true;
        }

        // 上传也当成 ajax 请求
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains("multipart")) {
            return true;
        }

        return false;
    }
}
